<template>
	<uni-collapse accordion  v-model="current" ref="collapse">
		<uni-collapse-item v-for="(item,i) in list" :key="i" :border="false"  title-border="none">
			<template v-slot:title>
				<view class="collapse-title">
					<view class="label">
						{{item.name}}
					</view>
					<view class="value">
						{{item.chooseIndex==undefined ? '': item.itemList[item.chooseIndex].name}}
					</view>
				</view>
			</template>
			<view class="content">
				<view class="item" v-for="(item2, j) in item.itemList" :class="item.chooseIndex==j?'choose':''" :key="j"
					@click="handleClickItems(item,i,j)">
					{{item2.name}}
				</view>
			</view>
		</uni-collapse-item>

	</uni-collapse>
</template>

<script setup>
	import {
		nextTick,
		ref,
		toRaw,
		watchEffect
	} from 'vue';
	const props = defineProps({
		data: {
			type: Array,
			default: () => ([])
		}
	})
	const emits = defineEmits(['end','change'])
	const list = ref([])
	const current = ref('-1')
	const collapse = ref({})

	//默认展开第一个选项
	watchEffect(() => {
		if (props.data.length) {
			// if(!props.data[0].itemList){
			// 	generateRadioList(props.data)
			// }
			list.value = [props.data[0]]
			nextTick(() => {
				setTimeout(function() {
					current.value = '0'
				}, 100);
			})
		}
	})
	
	function generateRadioList(list){
		list.forEach(item => {
			item.itemList = [
				{name:'有', amount: item.amount},
				{name:'无', amount: 0}
			]
		})
	}
	
	function handleClickItems(item, i, j) {
		item.chooseIndex = j
		const cur = +current.value
		if (cur < props.data.length - 1) {
				
			if(i === list.value.length-1){
				list.value.push(props.data[cur+1])
				nextTick(() => {
					current.value = cur+1+''
				})
			}else{
				// nextTick(() => {
				// 	current.value = list.value - 1
				// })
			}
			
		} else {
				current.value = '-1'
				emits('end')
		}
		const m = computedAmount()
		console.log('m',m)
		emits('change', m)
		nextTick(() => {
			uni.pageScrollTo({
				scrollTop:10000
			})
		})
	}
	function computedAmount(){
		return list.value.reduce((prev, cur) => {
			if(typeof cur.chooseIndex == 'number'){
				return cur.itemList[cur.chooseIndex].amount + prev
			}
			return prev
			
		},0)
	}
</script>

<style lang="scss" scoped>
	.collapse-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 30rpx;
		padding-right: 20rpx;

		.label {
			color: #333;
			font-size: 32rpx;
		}

		.value {
			color: #666;
			font-size: 28rpx;
		}
	}

	.content {
		display: flex;
		flex-wrap: wrap;
		padding-left: 30rpx;

		.item {
			color: #333;
			border-radius: 100px;
			padding: 15rpx 30rpx;
			background-color: #f5f5f5;
			font-size: 28rpx;
			margin-right: 30rpx;
			margin-bottom: 30rpx;
			min-width: 4em;
			text-align: center;

			&.choose {
				background-image: linear-gradient(to right, #2444EE, #3A75FF);
				color: #fff;
			}
		}
	}
</style>